package top.crossrun.notify;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;


public class MainActivity extends AppCompatActivity {

    ServiceConnection serviceConnection;
    NotifyServiceInterface notifySer;

    Switch shortMessage, phone, notification;
    EditText urlEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        checkP();

        initService();

    }

    private void initView() {
        urlEditText = findViewById(R.id.url);
        shortMessage = findViewById(R.id.short_message);
        phone = findViewById(R.id.phone);
        notification = findViewById(R.id.notification);

        findViewById(R.id.submit_url).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitSP("url", urlEditText.getText().toString());
//                notifySer.onAccpetMessage("测试", "123456", "dsdfasddf");
            }
        });

        shortMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                commitSP("message", isChecked);
                changeSwitchColor(shortMessage, isChecked);
                if (notifySer != null) {
                    try {
                        notifySer.setCheckMessage(isChecked);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        phone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                commitSP("phone", isChecked);
                changeSwitchColor(phone, isChecked);
                if (notifySer != null) {
                    try {
                        notifySer.setCheckPhone(isChecked);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        notification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                commitSP("notification", isChecked);
                changeSwitchColor(notification, isChecked);
                if (notifySer != null) {
                    try {
                        notifySer.setCheckNotification(isChecked);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                if (isChecked) {
                    checkNotify();
                }
            }
        });

        SharedPreferences sp = getSharedPreferences("notify", Context.MODE_PRIVATE);
        shortMessage.setChecked(sp.getBoolean("message", true));
        changeSwitchColor(shortMessage, shortMessage.isChecked());
        phone.setChecked(sp.getBoolean("phone", true));
        changeSwitchColor(phone, phone.isChecked());
        notification.setChecked(sp.getBoolean("notification", true));
        changeSwitchColor(notification, notification.isChecked());
        if (notification.isChecked()) {
            checkNotify();
        }
        urlEditText.setText(sp.getString("url", ""));

    }

    private void checkP() {
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 1);
        }
    }

    private void checkNotify() {
        String string = Settings.Secure.getString(getContentResolver(),
                "enabled_notification_listeners");
        if (!string.contains(MyNotificationListenerService.class.getName())) {
            startActivity(new Intent(
                    "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
        }
    }

    private void initService() {
        Intent intent = new Intent(this, NotifyService.class);
        Log.e("top.crossrun", Build.VERSION.SDK_INT + "");
        if (Build.VERSION.SDK_INT >= 26) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        serviceConnection = new ServiceConnection() {
            /**
             * Called when a connection to the Service has been established, with
             * the {@link IBinder} of the communication channel to the
             * Service.
             *
             * @param name    The concrete component name of the service that has
             *                been connected.
             * @param service The IBinder of the Service's communication channel,
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                notifySer = NotifyServiceInterface.Stub.asInterface(service);
            }

            /**
             * Called when a connection to the Service has been lost.  This typically
             * happens when the process hosting the service has crashed or been killed.
             * This does <em>not</em> remove the ServiceConnection itself -- this
             * binding to the service will remain active, and you will receive a call
             * to {@link #onServiceConnected} when the Service is next running.
             *
             * @param name The concrete component name of the service whose
             *             connection has been lost.
             */
            @Override
            public void onServiceDisconnected(ComponentName name) {
                notifySer = null;
            }
        };

        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }


    private void commitSP(String key, boolean value) {
        SharedPreferences sp = getSharedPreferences("notify", Context.MODE_PRIVATE);
        sp.edit().putBoolean(key, value).commit();
    }

    private void commitSP(String key, String value) {
        SharedPreferences sp = getSharedPreferences("notify", Context.MODE_PRIVATE);
        sp.edit().putString(key, value).commit();
    }

    private void changeSwitchColor(Switch s, boolean b) {
        //控制开关字体颜色
        if (b) {
            s.setSwitchTextAppearance(this, R.style.s_true);
        } else {
            s.setSwitchTextAppearance(this, R.style.s_false);
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
    }
}
